using System;
using System.Collections;
using System.Data;
using System.Globalization;
using System.Web.UI.WebControls;
using mojoPortal.Business;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using mojoPortal.Web;
using Resources;
using ud_Article.Business;
using mojoPortal.Business.WebHelpers;

namespace ud_Article.UI
{

    public partial class BlogCategoryView : mojoBasePage
    {
        #region Properties


        private int countOfDrafts;
        protected string feedBackLabel;
        protected int pageId = -1;
        protected int moduleId = -1;
        protected int categoryId = -1;
        protected string category = string.Empty;
        private Hashtable moduleSettings;
        protected ArticleConfiguration config = new ArticleConfiguration();
        protected Double timeOffset;
        protected TimeZoneInfo timeZone;
        private Module blogModule;
        private string DisqusSiteShortName = string.Empty;
        protected string EditLinkText = ArticleResources.BlogEditEntryLink;
        protected string EditLinkTooltip = ArticleResources.BlogEditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        protected string EditContentImage = WebConfigSettings.EditContentImage;        
        protected string DeleteLinkText = ArticleResources.ArticleDeleteLinkText;
        protected string DeleteLinkTooltip = ArticleResources.ArticleDeleteLinkText;
        protected string DeleteLinkImageUrl = string.Empty;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;

        #endregion

        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            Load += Page_Load;
            dlArchives.ItemCommand += dlArchives_ItemCommand;
            base.OnInit(e);
        }


        #endregion

        private void LoadPanels()
        {
            LoadSideContent(config.ShowLeftPanelSetting, config.ShowRightPanelSetting, config.ShowTopPanelSetting, config.ShowBottomPanelSetting, config.ShowNumberModuleSetting);
        }


        void dlArchives_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                Article article = new Article(int.Parse(e.CommandArgument.ToString()));

                article.ContentChanged += article_ContentChanged;
                article.Delete();
                FriendlyUrl.DeleteByPageGuid(article.BlogGuid);
                CurrentPage.UpdateLastModifiedTime();
                SiteUtils.QueueIndexing();

                //WebUtils.SetupRedirect(this, SiteUtils.GetCurrentPageUrl());
                WebUtils.SetupRedirect(this, Request.Url.ToString());
            }
        }

        void article_ContentChanged(object sender, ContentChangedEventArgs e)
        {
            IndexBuilderProvider indexBuilder = IndexBuilderManager.Providers["ArticleIndexBuilderProvider"];
            if (indexBuilder != null)
            {
                indexBuilder.ContentChangedHandler(sender, e);
            }
        }

        private void Page_Load(object sender, EventArgs e)
        {

            if (!UserCanViewPage(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            LoadSettings();
            SetupCss();
            AddConnoicalUrl();
            PopulateLabels();


            if (!config.NavigationOnRight)
            {
                divNav.CssClass = "blognavleft";
                divblog.CssClass = "blogcenter-leftnav";

            }

            if (!IsPostBack)
            {
                if ((moduleId > -1) && (categoryId > -1))
                {
                    using (IDataReader reader = Article.GetCategory(categoryId))
                    {
                        if (reader.Read())
                        {
                            category = reader["Category"].ToString();
                        }
                    }

                    moduleTitle.Header = Page.Server.HtmlEncode(category);

                    if (blogModule != null)
                    {
                        Title = SiteUtils.FormatPageTitle(siteSettings,
                            blogModule.ModuleTitle + " - " + ArticleResources.BlogCategoriesPrefixLabel + category);

                        MetaDescription = string.Format(CultureInfo.InvariantCulture,
                            ArticleResources.CategoryMetaDescriptionFormat,
                            blogModule.ModuleTitle, category);
                    }

                    using (IDataReader reader = Article.GetEntriesByCategory(moduleId, categoryId))
                    {
                        dlArchives.DataSource = reader;
                        dlArchives.DataBind();
                    }

                    PopulateNavigation();

                }
            }


        }

        protected string FormatBlogUrl(string itemUrl, int itemId)
        {
            if (itemUrl.Length > 0)
                return SiteRoot + itemUrl.Replace("~", string.Empty);

            return SiteRoot + "/Article/ViewPost.aspx?pageid=" + pageId.ToInvariantString()
                + "&ItemID=" + itemId.ToInvariantString()
                + "&mid=" + moduleId.ToInvariantString();

        }


        private void PopulateLabels()
        {
            feedBackLabel = ArticleResources.BlogFeedbackLabel;
            mojoBasePage basePage = Page as mojoBasePage;
            if (basePage != null)
            {
                if (!basePage.UseTextLinksForFeatureSettings)
                {
                    EditLinkImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                    DeleteLinkImage = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
                }

            }
        }


        private void PopulateNavigation()
        {
            Feeds.Config = config;
            Feeds.PageId = pageId;
            Feeds.ModuleId = moduleId;
            Feeds.Visible = config.ShowFeedLinks;

            //tags.CanEdit = IsEditable;
            tags.PageId = pageId;
            tags.ModuleId = moduleId;
            tags.SiteRoot = SiteRoot;
            tags.RenderAsTagCloud = config.UseTagCloudForCategories;

            archive.PageId = pageId;
            archive.ModuleId = moduleId;
            archive.SiteRoot = SiteRoot;

            stats.PageId = pageId;
            stats.ModuleId = moduleId;
            stats.CountOfDrafts = countOfDrafts;
            stats.Visible = config.ShowStatistics;
        }

        protected string FormatBlogDate(DateTime startDate)
        {
            if (timeZone != null)
            {
                return TimeZoneInfo.ConvertTimeFromUtc(startDate, timeZone).ToString(config.DateTimeFormat);

            }

            return startDate.AddHours(timeOffset).ToString(config.DateTimeFormat);

        }

        private void LoadSettings()
        {
            DisqusSiteShortName = config.DisqusSiteShortName.Length > 0
                                      ? config.DisqusSiteShortName
                                      : siteSettings.DisqusSiteShortName;

            if (DisqusSiteShortName.Length > 0)
            {
                stats.ShowCommentCount = false;
            }

            pnlStatistics.Visible = config.ShowStatistics;

            divNav.Visible = true;
            if (!divNav.Visible)
            {
                divblog.CssClass = "blogcenter-nonav";
            }

            countOfDrafts = Article.CountOfDrafts(moduleId);
        }

        private void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet != null)
            {
                if (stylesheet.FindControl("blogcss") == null)
                {
                    Literal cssLink = new Literal
                                          {
                                              ID = "blogcss",
                                              Text = @"<link href='"
                                                     + SiteUtils.GetSkinBaseUrl()
                                                     +
                                                     @"blogmodule.css' type='text/css' rel='stylesheet' media='screen' />"
                                          };

                    stylesheet.Controls.Add(cssLink);
                }
            }
        }

        private void AddConnoicalUrl()
        {
            if (Page.Header == null) { return; }

            Literal link = new Literal
                               {
                                   ID = "blogcaturl",
                                   Text = @"<link rel='canonical' href='"
                                          + SiteRoot
                                          + @"/Article/ViewCategory.aspx?cat="
                                          + categoryId.ToInvariantString()
                                          + @"&amp;mid=" + moduleId.ToInvariantString()
                                          + @"&amp;pageid=" + pageId.ToInvariantString()
                                          + @"' />"
                               };

            Page.Header.Controls.Add(link);

        }

        private void LoadParams()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            categoryId = WebUtils.ParseInt32FromQueryString("cat", categoryId);
            pnlContainer.ModuleId = moduleId;
            blogModule = GetModule(moduleId);
            moduleSettings = ModuleSettings.GetModuleSettings(moduleId);
            config = new ArticleConfiguration(moduleSettings);
            AnalyticsSection = ConfigHelper.GetStringProperty("AnalyticsBlogSection", "blog");
        }

    }
}
